<?php

namespace App\Http\Controllers\Supervisor;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Supervisor;

class TwowayChoiceController extends Controller
{

    public function index() {
        $user = \Auth::user();
        $supervisor = $user->supervisor;
        $approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();
        return view('supervisor.twowaychoiceresult', compact("approvedStudents", "user"));
    }

    public function create()
    {
    	$user = \Auth::user();
    	$supervisor = $user->supervisor;
    	$approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();
        $applicationStudents = $supervisor->students()->wherePivot("isApproved", false)->get();
    	return view('supervisor.twowaychoice', compact("applicationStudents", "approvedStudents", "user", "supervisor"));
    }

    public function store(Request $request)
    {
    	$user = \Auth::user();
    	$supervisor = $user->supervisor;
        $approvedCount = $supervisor->students()->wherePivot("isApproved", true)->count();
    	
  		$student_ids = $request->input('student');
        if (! is_array($student_ids)) {
            return Redirect::to('supervisor/twowaychoice');
        }

        if (count($student_ids) + $approvedCount > $supervisor->quota) {
            return Redirect::to('supervisor/twowaychoice');
        }

  		$sync = Array();
        $supervisor->students()->detach($student_ids);
  		foreach ($student_ids as $student_id) {
  			$sync[$student_id] = array("isApproved" =>true);
  		}
    	$supervisor->students()->attach($sync);

        //删除未审批的老师
        $approvedStudents = $supervisor->students()->wherePivot("isApproved", true)->get();

        foreach($approvedStudents as $approvedStudent) {
            $approvedStudent->supervisors()->sync([$supervisor->id => array("isApproved" => true)]);
        }
    	return Redirect::to('supervisor/twowaychoice');
    }

}
